package com.cuje.coolrtc.activity;

import android.Manifest;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.cuje.coolrtc.App;
import com.cuje.coolrtc.R;
import com.cuje.coolrtc.base.BaseActivity;
import com.cuje.coolrtc.utils.PermissionChecker;
import com.p2p.core.P2PFacade;
import com.p2p.define.P2PRoomType;
import com.p2p.listener.P2PGlobalListener;
import com.p2p.listener.P2PRoomListener;
import com.p2p.model.P2PError;
import com.p2p.model.P2PRoom;
import com.p2p.model.P2PUser;

import org.webrtc.MediaStream;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRendererGui;

import java.util.List;


public class VideoActivity extends BaseActivity implements P2PGlobalListener {
    private final static String TAG = VideoActivity.class.getCanonicalName();
    /**
     * 本地video未连接时的控件大小个位置
     */
    private static final int LOCAL_X_CONNECTING = 0;
    private static final int LOCAL_Y_CONNECTING = 0;
    private static final int LOCAL_WIDTH_CONNECTING = 100;
    private static final int LOCAL_HEIGHT_CONNECTING = 100;
    /**
     * 本地video连接后的控件大小个位置
     */
    private static final int LOCAL_X_CONNECTED = 72;
    private static final int LOCAL_Y_CONNECTED = 72;
    private static final int LOCAL_WIDTH_CONNECTED = 25;
    private static final int LOCAL_HEIGHT_CONNECTED = 25;
    /**
     * 远程video连接后的控件大小个位置
     */
    private static final int REMOTE_X = 0;
    private static final int REMOTE_Y = 0;
    private static final int REMOTE_WIDTH = 100;
    private static final int REMOTE_HEIGHT = 100;
    /**
     * video控件的展示方式，SCALE_ASPECT_FILL（在保持纵横比的前提下，缩放图片，使视频充满容器）
     */
    private VideoRendererGui.ScalingType scalingType = VideoRendererGui.ScalingType.SCALE_ASPECT_FILL;
    /**
     * 画布
     */
    private GLSurfaceView vsv;
    /**
     * 显示本地和远程视频的控件
     */
    private VideoRenderer.Callbacks localRender;
    private VideoRenderer.Callbacks remoteRender;
    /**
     * 信令服务器的地址和RTC客户端
     */
    private String mSocketAddress;
    /**
     * 检查权限
     */
    private static final String[] RequiredPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
    protected PermissionChecker permissionChecker = new PermissionChecker();

    private Context mContext;
    private P2PRoom mRoom;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_video);
        mSocketAddress = getResources().getString(R.string.host);
        vsv = findViewById(R.id.glview_call);
        vsv.setPreserveEGLContextOnPause(true);
        vsv.setKeepScreenOn(true);
        VideoRendererGui.setView(vsv, new Runnable() {
            @Override
            public void run() {
                P2PFacade.onCreate(VideoActivity.this, App.getUid(), App.getUserName());
            }
        });

        // local and remote render
        remoteRender = VideoRendererGui.create(
                REMOTE_X, REMOTE_Y,
                REMOTE_WIDTH, REMOTE_HEIGHT, scalingType, false);
        localRender = VideoRendererGui.create(
                LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING,
                LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING, scalingType, true);
        checkPermissions();
        findViewById(R.id.bt_send_msg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText et = findViewById(R.id.et_send_msg);
                String msg = et.getText().toString();
                if (msg.length() > 0) {
                    mRoom.dataChannelTalk(msg);
                }
            }
        });
    }

    private void checkPermissions() {
        permissionChecker.verifyPermissions(this, RequiredPermissions, new PermissionChecker.VerifyPermissionsCallback() {
            @Override
            public void onPermissionAllGranted() {

            }

            @Override
            public void onPermissionDeny(String[] permissions) {
                makeShortToast("Please grant required permissions.");
            }
        });
    }


    @Override
    public void onInitSuccess() {
        P2PFacade.joinRoom("3456", P2PRoomType.Media, new P2PRoomListener() {
            @Override
            public boolean checkPermission() {
                return false;
            }

            @Override
            public void onJoinSuccess(P2PRoom room) {
                mRoom = room;
            }

            @Override
            public void onStatusChanged(P2PUser user, String newStatus) {

            }

            @Override
            public void onLocalStream(MediaStream localStream) {
                localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
                VideoRendererGui.update(localRender,
                        LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING,
                        LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING,
                        scalingType, false);
            }

            @Override
            public void onAddRemoteStream(P2PUser user) {
                user.getRemoteStream().videoTracks.get(0).addRenderer(new VideoRenderer(remoteRender));
                VideoRendererGui.update(remoteRender,
                        REMOTE_X, REMOTE_Y,
                        REMOTE_WIDTH, REMOTE_HEIGHT, scalingType, false);
                VideoRendererGui.update(localRender,
                        LOCAL_X_CONNECTED, LOCAL_Y_CONNECTED,
                        LOCAL_WIDTH_CONNECTED, LOCAL_HEIGHT_CONNECTED,
                        scalingType, false);
            }

            @Override
            public void onRemoveRemoteStream(P2PUser user) {
                VideoRendererGui.update(localRender,
                        LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING,
                        LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING,
                        scalingType, false);
            }

            @Override
            public void onDataChannelTextMessage(P2PUser other, String message) {
                makeShortToast(other.getName() + ":" + message);
            }

            @Override
            public void onUserJoined(P2PUser other) {

            }

            @Override
            public void onUserLeft(P2PUser other) {

            }
        });
    }

    @Override
    public void onInitFailure(P2PError error) {

    }

    @Override
    public void onRoomCreateSuccess(P2PRoom room) {

    }

    @Override
    public void onRoomCreateFailure(P2PRoom room, P2PError error) {

    }

    @Override
    public void onLeaveRoomSuccess(P2PRoom room, P2PUser self) {

    }

    @Override
    public void onLeaveRoomFailure(P2PRoom room, P2PError error) {

    }

    @Override
    public void onGetUserListSuccess(P2PRoom room, List<P2PUser> userList) {

    }

    @Override
    public void onGetUserListFailure(P2PRoom room, P2PError error) {

    }

    @Override
    public void onGetRoomListSuccess(String groupId, List<P2PRoom> roomList) {

    }

    @Override
    public void onGetRoomListFailure(String groupId, P2PError error) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mRoom != null) {
            mRoom.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mRoom != null) {
            mRoom.onResume();
        }
    }

    @Override
    protected void onDestroy() {
        if (mRoom != null) {
//            if (localRender != null) {
//                VideoRendererGui.remove(localRender);
//            }
//            if (remoteRender != null) {
//                VideoRendererGui.remove(remoteRender);
//            }
            mRoom.onDestroy();
        }
        super.onDestroy();
    }
}
